<?php
namespace app\admin\controller;

use app\common\helper\Uploader;
use app\common\model\data\SystemMusicSpiderModel;
use app\common\model\project_model\AlbumMusicCategoryModel;
use app\common\model\project_model\SystemMusicCategoryModel;
use app\common\model\project_model\SystemMusicModel;
use app\yxwadmin\controller\Admin;
use app\admin\model\validate\SystemMusic as ValidateMusic;
use think\Exception;

class SystemMusic extends Admin
{

    public $error_msg = '';

    /**
     * 首页
     * @return string
     * @throws \think\Exception
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 初始化表格
     * 关键字搜索
     * 分页
     * @throws
     * @return mixed
     */
    public function getList()
    {
        $limit = input('limit','0');
        $offset = input('offset','0');
        $sortName = input('sortName','id');
        $sortOrder = input('sortOrder','desc');
        $keyword = input('keywords','');

        $model = new SystemMusicModel();
        if ($keyword) {
            $count = $model->where('title|singer|mp3_url|cate_name', 'like', '%' . $keyword . '%')->count();
            $list = $model
               ->where('title|singer|mp3_url|cate_name', 'like', '%' . $keyword . '%')
               ->order([$sortName => $sortOrder])
               ->limit($offset . ',' . $limit)
               ->select();
        } else {
            $count = $model->count(); //查询满足要求的总记录数
            $list = $model
                ->order(array($sortName=>$sortOrder))
                ->limit($offset.','.$limit)
                ->select();
        }

        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function add() {
        if (request()->isPost()) {
            $validate = new ValidateMusic();
            $data = $_REQUEST;
            $data['created_time'] = date('Y-m-d H:i:s', time());
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            $res = $validate->check($data);
            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            $model = new SystemMusicModel($data);
            $res = $model->allowField(true)->save();
            if (!$res) {
                $this->error_msg = $model->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }
            return json(['code' => 1, 'msg' => '新增成功', 'data' => null]);

        } else {
            $this->assign('status_list', SystemMusicModel::statusList());
            $this->assign('category_list', SystemMusicCategoryModel::categoryList());
            return $this->fetch();
        }
    }

    public function edit() {
        $id = $_REQUEST['id'];
        $model = new SystemMusicModel();

        if (request()->isPost()) {
            $validate = new ValidateMusic();
            $data = $_REQUEST;
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            $res = $validate->check($data);

            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            $res = $model->allowField(true)->save($data,['id' => $id]);

            if ($res === false) {
                $this->error_msg = $model->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            return json(['code' => 1, 'msg' => '编辑成功', 'data' => null]);

        } else {
            $this->assign('status_list', SystemMusicModel::statusList());
            $this->assign('category_list', SystemMusicCategoryModel::categoryList());
            $Rs = $model->where(['id' => $id])->find();
            $this->assign('Rs', $Rs);
            return $this->fetch();
        }
    }

    public function view() {
        $id = input('id/d');
        $model = new SystemMusicModel();
        $Rs = $model->where(['id' => $id])->find();
        $this->assign('Rs', $Rs);
        return $this->fetch();
    }

    public function get_mp3_url() {
        $music_id = input('music_id');
        if (empty($music_id)) {
            return json(['code' => 0, 'msg' => '没有参数music_id']);
        }
        $url = SystemMusicSpiderModel::getQQPlayUrl($music_id);

        if (!$url) {
            return json(['code' => 0, 'msg' => SystemMusicSpiderModel::$err_msg]);
        }
        return json(['code' => 1, 'msg' => 'success', 'mp3_url' => $url]);
    }

    /**
     * 锁定
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function lock()
    {
        $id = input('id/d');
        $model = new SystemMusicModel();
        $where = ['id'=>$id];
        $data = $model->where($where)->find();
        $status = SystemMusicModel::STATUS_LOCK;
        if ($data['status'] == SystemMusicModel::STATUS_LOCK) {
            $status = SystemMusicModel::STATUS_OK;
        }
        $res = $model->save(['status' => $status], $where);
        if ($res) {
            $ret['code']=1;
            $ret['msg']='操作成功';
        } else {
            $ret['code']=0;
            $ret['msg']='服务器繁忙';
        }
        return json($ret);
    }

    /**
     * 加入系统音乐
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function inner() {
        $mid = input('music_id', '');
        if (empty($mid)) {
            return json(['code' => 0, 'msg' => '没有music_id参数']);
        }
        $res = SystemMusicSpiderModel::getQQPlayUrl($mid);

        if (!$res) {
            return json(['code' => 0, 'msg' => SystemMusicSpiderModel::$err_msg]);
        }
        try {
            if (!$res = $this->download($res)) {
                throw new Exception('下载音乐失败!');
            }
            $uploader = new Uploader();
            if(!$res = $uploader->uploadMusic($res)) {
                throw new Exception('上传失败!');
            }
            // 入库
            $musicM = new SystemMusicModel();
            $res = $musicM->save(['mp3_url' => $res, 'type' => SystemMusicModel::TYPE_SYSTEM], ['music_id' => $mid]);
            if (!$res) {
                throw new Exception('更新库失败!');
            }
            return json(['code' => 1, 'msg' => 'success']);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 从远程链接下载资源到本地
     *
     * @param $res
     * @return string
     */
    public function download($res) {
        $ch = curl_init();//初始化一个cURL会话
        curl_setopt($ch,CURLOPT_URL,$res);//抓取url
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//是否显示头信息
        curl_setopt($ch,CURLOPT_SSLVERSION,3);//传递一个包含SSL版本的长参数
        $data = curl_exec($ch);// 执行一个cURL会话
        $error = curl_error($ch);//返回一条最近一次cURL操作明确的文本的错误信息。
        if ($error) {
            return false;
        }
        curl_close($ch);//关闭一个cURL会话并且释放所有资源
        $fileName = ROOT_PATH . 'runtime/temp/' . time() . mt_rand(1000, 9999);
        $file = fopen($fileName,"w+");
        fputs($file,$data);//写入文件
        fclose($file);
        return $fileName;
    }

}